﻿using famails.bus;
using famails.common;
using famails.dto;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{
    public partial class PackageChange : System.Web.UI.Page
    {
        protected string Title;
        ClientBUS clientbus;
        ClientRegisterBUS clientRegister;
        ClientFunctionBUS clientFunction;
        PackageBUS pkgBus;
        PackageCostBUS pkgCostBus;
        PackageFunctionBUS pkgFunctionBus;
        PackageLimitBUS pkglimitBus;
        FunctionBUS function;
        string dayleft, expireDatesession;
        UserLoginDTO userLogin = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            if (!IsPostBack)
            {
                upgradeservices.Visible = false;
                extendbox.Visible = false;
                LoadData();
                LoadPackageTime();
                LoadAvailableService();
            }
        }
        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~");//test confict
            return null;
        }
        private void LoadAvailableService()
        {
            try
            {
                if (Request.QueryString["type"] != null)
                {
                    int user = Convert.ToInt32(userLogin.UserId);
                    clientbus = new ClientBUS();
                    DataTable dtClient = new DataTable();
                    dtClient = clientbus.GetByID(user);
                    string email = dtClient.Rows[0]["email"].ToString();
                    DateTime dateexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
                    int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                    int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                    clientRegister = new ClientRegisterBUS();
                    DataTable dtClientRegister = new DataTable();
                    dtClientRegister = clientRegister.GetbyID(registerId);
                    string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                    DataTable dtpackage = new DataTable();
                    pkgBus = new PackageBUS();
                    dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
                    int packagelimitid = Convert.ToInt32(dtClientRegister.Rows[0]["limitid"].ToString());
                    DataTable dtlimit = new DataTable();
                    pkglimitBus = new PackageLimitBUS();
                    dtlimit = pkgBus.GetAvailablePackage(Convert.ToInt32(packageid));
                    //lblTenGoi.Text = dtlimit.Rows[0]["namepackagelimit"].ToString();
                    //int idPackage = Convert.ToInt32(dtlimit.Rows[0]["limitId"]);
                    //pkglimitBus = new PackageLimitBUS();
                    //DataTable dtAvailable = pkglimitBus.GetAvailablePackage(idPackage);
                    ddlUpgradeServices.DataSource = dtlimit;
                    ddlUpgradeServices.DataTextField = "packageName";
                    ddlUpgradeServices.DataValueField = "packageId";
                    ddlUpgradeServices.DataBind();
                    ddlUpgradeServices.SelectedValue = packageid + "";
                }
            }
            catch (Exception ex) { common.Common.logs(userLogin.Username + " - LoadAvailableService", ex, Common.logType.error); }
        }
        private void LoadData()
        {
            if (Request.QueryString["type"] != null)
            {
                string status = Request.QueryString["type"].ToString();
                int userid = Convert.ToInt32(userLogin.UserId);
                if (status == "extend")
                {
                    #region Extend
                    lblTitle.Text = "Gia hạn dịch vụ";
                    extendbox.Visible = true;
                    upgradeservices.Visible = false;
                    if (userid != null)
                    {
                        int user = userid;//Convert.ToInt32(Request.QueryString["user"].ToString());
                        clientbus = new ClientBUS();
                        DataTable dtClient = new DataTable();
                        dtClient = clientbus.GetByID(user);
                        string email = dtClient.Rows[0]["email"].ToString();
                        DateTime dateexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
                        int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                        int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                        clientRegister = new ClientRegisterBUS();
                        DataTable dtClientRegister = new DataTable();
                        dtClientRegister = clientRegister.GetbyID(registerId);
                        string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                        DataTable dtpackage = new DataTable();
                        pkgBus = new PackageBUS();
                        dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
                        int packagelimitid = Convert.ToInt32(dtClientRegister.Rows[0]["limitId"].ToString());
                        DataTable dtlimit = new DataTable();
                        pkglimitBus = new PackageLimitBUS();
                        dtlimit = pkglimitBus.GetByUserIdPackageLimit(packagelimitid);
                        DateTime NgayHetHan = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
                        string todays = DateTime.Now.ToString("yyyy-MM-dd");
                        DateTime today = Convert.ToDateTime(todays);
                        DateTime expireDay = Convert.ToDateTime(NgayHetHan);
                        if (today > expireDay)
                        {
                            lblExpireDate.Text = NgayHetHan.ToString("dd/MM/yyyy") + " (Đã hết hạn) ";
                        }
                        else if (expireDay > today)
                        {
                            string totalday = (expireDay - today).TotalDays.ToString();
                            dayleft = totalday;
                            lblExpireDate.Text = NgayHetHan.ToString("dd/MM/yyyy") + "(Còn " + totalday + " ngày)";
                            ddlExtend.Enabled = false;
                            Session["totalDayLeft"] = totalday;
                        }
                        else if (expireDay == today)
                        {
                            double totalday = (expireDay - today).TotalMinutes;
                            if (totalday > 0)
                            {
                                lblExpireDate.Text = NgayHetHan.ToString("dd/MM/yyyy") + "(Còn " + totalday + " phút)";
                                ddlExtend.Enabled = false;
                            }
                            else
                            {
                                lblExpireDate.Text = NgayHetHan.ToString("dd/MM/yyyy") + " (Đã hết hạn) ";
                            }
                        }
                    }
                    #endregion
                }
                else if (status == "upgrade")
                {
                    #region Upgrade
                    lblTitle.Text = "Nâng cấp dịch vụ";
                    extendbox.Visible = false;
                    upgradeservices.Visible = true;
                    //ddlUpgradeTime.Enabled = false;
                    optionchkbox.Attributes.Add("disabled", "true");
                    if (userid != null)
                    {
                        int user = userid;
                        clientbus = new ClientBUS();
                        DataTable dtClient = new DataTable();
                        dtClient = clientbus.GetByID(user);
                        string email = dtClient.Rows[0]["email"].ToString();
                        DateTime dateexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
                        int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                        int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                        clientRegister = new ClientRegisterBUS();
                        DataTable dtClientRegister = new DataTable();
                        dtClientRegister = clientRegister.GetbyID(registerId);
                        string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                        DataTable dtpackage = new DataTable();
                        pkgBus = new PackageBUS();
                        dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
                        int packagelimitid = Convert.ToInt32(dtClientRegister.Rows[0]["limitid"].ToString());
                        DataTable dtlimit = new DataTable();
                        pkglimitBus = new PackageLimitBUS();
                        dtlimit = pkglimitBus.GetByUserIdPackageLimit(packagelimitid);
                        lblTenGoi.Text = dtpackage.Rows[0]["packageName"].ToString();
                        #region loadpackage
                        pkgFunctionBus = new PackageFunctionBUS();
                        DataTable dtfunction = pkgFunctionBus.GetFunctionbyPackageId(Convert.ToInt32(packageid));
                        rptListOptionsUpgrade.DataSource = dtfunction;
                        rptListOptionsUpgrade.DataBind();
                        pkgBus = new PackageBUS();
                        DataTable dtPackage = pkgBus.GetById(Convert.ToInt32(packageid));
                        int currentLimitID = Convert.ToInt32(dtPackage.Rows[0]["limitId"].ToString());
                        pkglimitBus = new PackageLimitBUS();
                        DataTable dtTempp = pkglimitBus.GetAll();
                        ddlPackageLimitUpgrade.DataSource = dtTempp;
                        ddlPackageLimitUpgrade.DataTextField = "namepackagelimit";
                        ddlPackageLimitUpgrade.DataValueField = "limitId";
                        ddlPackageLimitUpgrade.DataBind();
                        ddlPackageLimitUpgrade.SelectedValue = currentLimitID + "-" + dtTempp.Select("id="+currentLimitID)[0]["cost"];
                        #endregion

                        ddlUpgradeServices.SelectedValue=dtClientRegister.Rows[0]["packageid"]+"";
                        DateTime today = DateTime.Now;
                        DateTime dayexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
                        string totaldayleft, hoursleft;
                        if (dayexpire > today)
                        {
                            totaldayleft = Math.Round((dateexpire - today).TotalDays).ToString();
                            hoursleft = Math.Round(Convert.ToDouble((dateexpire - today).TotalHours - (24 * Convert.ToDouble(totaldayleft)))).ToString();
                            double comparetime = Convert.ToDouble(totaldayleft);
                            double comparehours = Convert.ToDouble(hoursleft);
                            if (comparetime >= 1 && comparehours > 0)
                            {
                                lblTimeLeft.Text = dateexpire.ToString("dd/MM/yyyy") + " (Còn " + totaldayleft + " ngày " + hoursleft + " giờ)";
                                dayleft = totaldayleft;
                                Session["totalDayLeft"] = totaldayleft;
                            }
                            else if (comparetime >= 1 && comparehours <= 0)
                            {
                                lblTimeLeft.Text = dateexpire.ToString("dd/MM/yyyy") + " (Còn " + totaldayleft + " ngày)";
                                dayleft = totaldayleft;
                                Session["totalDayLeft"] = totaldayleft;
                            }
                            else
                            {
                                totaldayleft = (dateexpire - today).TotalHours.ToString();
                                comparetime = Convert.ToDouble(totaldayleft);
                                lblTimeLeft.Text = "Còn " + Math.Round(comparetime) + " giờ";
                                //sdayleft = totaldayleft;
                            }
                        }
                        else if (dayexpire < today)
                        {
                            lblTimeLeft.Text = dayexpire + " (Đã hết hạn)";
                        }
                        double feeRemain = GetFeeRemain(Convert.ToInt32(userLogin.UserId));
                        lblFeeRemain.Text = feeRemain + "$";
                        TinhTien();
                        //btnUpgrade.Visible = false;
                    }
                    #endregion
                }
                else if (status == "editoption")
                {
                    #region EditOption
                    lblTitle.Text = "Thay đổi chức năng dịch vụ";
                    extendbox.Visible = false;
                    upgradeservices.Visible = false;
                    changeoptionbox.Visible = true;
                    if (userid != null)
                    {
                        int user = userid;
                        clientbus = new ClientBUS();
                        DataTable dtClient = new DataTable();
                        dtClient = clientbus.GetByID(user);
                        string email = dtClient.Rows[0]["email"].ToString();
                        DateTime dateexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
                        int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                        int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                        clientRegister = new ClientRegisterBUS();
                        DataTable dtClientRegister = new DataTable();
                        dtClientRegister = clientRegister.GetbyID(registerId);
                        string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                        pkgFunctionBus = new PackageFunctionBUS();
                        DataTable dtfunction = pkgFunctionBus.GetFunctionbyPackageId(Convert.ToInt32(packageid));
                        DataTable dtFunctionTemmp = new DataTable();
                        dtFunctionTemmp.Columns.Add("functionId");
                        dtFunctionTemmp.Columns.Add("functionName");
                        dtFunctionTemmp.Columns.Add("cost");
                        dtFunctionTemmp.Columns.Add("isDefault");
                        foreach (DataRow drfunction in dtfunction.Rows)
                        {
                            int id = Convert.ToInt32(drfunction["functionId"].ToString());
                            function = new FunctionBUS();
                            DataTable dtTemp = function.GetByUserId(id);
                            DataRow dr = dtFunctionTemmp.NewRow();
                            dr["functionId"] = dtTemp.Rows[0]["functionId"].ToString();
                            dr["functionName"] = dtTemp.Rows[0]["functionName"].ToString();
                            dr["cost"] = dtTemp.Rows[0]["cost"].ToString();
                            dr["isDefault"] = dtTemp.Rows[0]["isDefault"].ToString();
                            dtFunctionTemmp.Rows.Add(dr);
                        }
                        rptListOptions.DataSource = dtFunctionTemmp;
                        rptListOptions.DataBind();
                        pkgBus = new PackageBUS();
                        DataTable dtPackage = pkgBus.GetById(Convert.ToInt32(packageid));
                        int currentLimitID = Convert.ToInt32(dtPackage.Rows[0]["limitId"].ToString());
                        pkglimitBus = new PackageLimitBUS();
                        DataTable dtTempp = pkglimitBus.GetAll();
                        ddlLimitPackage.DataSource = dtTempp;
                        ddlLimitPackage.DataTextField = "namepackagelimit";
                        ddlLimitPackage.DataValueField = "limitId";
                        ddlLimitPackage.DataBind();
                        ddlLimitPackage.SelectedValue = currentLimitID.ToString();
                        pkglimitBus = new PackageLimitBUS();
                        DataTable dtCosts = pkglimitBus.GetByUserIdPackageLimit(currentLimitID);
                        int value2 = Convert.ToInt32(dtCosts.Rows[0]["cost"].ToString());
                        foreach (RepeaterItem rptItems in rptListOptions.Items)
                        {
                            CheckBox chk = (CheckBox)rptItems.FindControl("chkOptions");
                            Label lbl = (Label)rptItems.FindControl("lblCost");
                            if (chk.Checked == true)
                            {
                                value2 += Convert.ToInt32(lbl.Text);
                            }
                        }
                        lblSumCost.Text = (value2).ToString();
                    }
                    #endregion
                }
            }
        }
        protected void ddlExtend_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int user = Convert.ToInt32(userLogin.UserId);
                clientbus = new ClientBUS();
                DataTable dtClient = new DataTable();
                dtClient = clientbus.GetByID(user);
                int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                clientRegister = new ClientRegisterBUS();
                DataTable dtClientRegister = new DataTable();
                dtClientRegister = clientRegister.GetbyID(registerId);
                cost = 0;
                double.TryParse(dtClientRegister.Rows[0]["feepermonth"] + "", out cost);
                DateTime from = Convert.ToDateTime(dtClient.Rows[0]["expiredate"]);
                if (expireDate.Date < DateTime.Now.Date)
                    from = DateTime.Now.Date;

                ViewState["from"] = from;
                var TimeId = ddlExtend.SelectedValue;
                int month, discount;
                if (int.TryParse(TimeId.Split('-')[2], out month) && month > 0)
                {
                    int.TryParse(TimeId.Split('-')[1], out discount);
                    cost = cost * month - (cost * month * discount / 100);
                    costperday = cost / (DateTime.Now.AddMonths(month) - DateTime.Now.Date).Days;
                    costpermonth = cost / month;
                    expireDate = from.AddMonths(month);
                    lblExpireDate.Text = expireDate.ToString("dd/MM/yyyy");
                    ViewState["to"] = expireDate;
                    ViewState["cost"] = cost;
                    ViewState["costpermonth"] = costpermonth;
                    ViewState["costperday"] = costperday;
                }
                lblExtendCost.Text = cost.ToString("#,###.000'$'");
            }

            catch (Exception ex)
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = "Có lỗi xảy ra trong quá trình gia hạn</br>" + ex.Message;
                common.Common.logs(userLogin.Username + "-ddlExtend_SelectedIndexChanged", ex, Common.logType.error);
            }
        }
        protected void btnGiahan_Click(object sender, EventArgs e)
        {
            try
            {
                int packageTimeId = Convert.ToInt32(ddlExtend.SelectedValue.Split('-')[0]);
                if (packageTimeId <= 0)
                {
                    pnSuccess.Visible = false;
                    pnError.Visible = true;
                    lblError.Text = "Chưa chọn gói thời gian" ;
                    return;
                }
                ClientRegisterBUS bus = new ClientRegisterBUS();
                double.TryParse(ViewState["cost"]+"",out cost);
                double.TryParse(ViewState["costpermonth"]+"",out costpermonth);
                double.TryParse(ViewState["costperday"]+"",out costperday);
                bus.Extend(userLogin.ClientID, Math.Round(cost, 3), Math.Round(costperday, 3), Math.Round(costpermonth, 3), Convert.ToDateTime(ViewState["from"]), Convert.ToDateTime(ViewState["to"]), Convert.ToInt32(ddlExtend.SelectedValue.Split('-')[0]));
                LoadData();

                pnError.Visible = false;
                pnSuccess.Visible = true;
                lblSuccess.Text = "Đã gia hạn thành công!!!";
                common.Common.logs(userLogin.Username + "-Đã gia hạn thành công!!!", null, Common.logType.info);
            }

            catch (Exception ex)
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = "Có lỗi xảy ra trong quá trình gia hạn</br>" + ex.Message;
                common.Common.logs(userLogin.Username + "-ddlExtend_SelectedIndexChanged", ex, Common.logType.error);
            }
        }
        protected void btnUpgrade_Click(object sender, EventArgs e)
        {
            try
            {
                string message = CheckBeforeUpgrade();
                if (message.Length > 0)
                {
                    pnSuccess.Visible = false;
                    pnError.Visible = true;
                    lblError.Text = message;
                    return;
                }
                TinhTien();
                string status = Request.QueryString["type"].ToString();
                int registerType;
                if (status == "extend")
                {
                    registerType = 1;
                }
                else if (status == "upgrade")
                {
                    registerType = 2;
                }
                else if (status == "addfunction")
                {
                    registerType = 3;
                }
                else
                {
                    registerType = 0;
                }
                clientRegisterdto dto = new clientRegisterdto();
                dto.clientId = userLogin.ClientID;
                dto.from = DateTime.Now.Date;
                dto.to = expireDate;
                dto.totalFee = cost;
                dto.FeePerDay = Math.Round(costperday, 3);
                dto.FeePerMonth = Math.Round(costpermonth, 3);
                dto.registerType = registerType;
                dto.packageId = Convert.ToInt32(ddlUpgradeServices.SelectedValue.Split('-')[0]);
                dto.limitId = Convert.ToInt32(ddlPackageLimitUpgrade.SelectedValue.Split('-')[0]);
                dto.packageTimeId = Convert.ToInt32(ddlUpgradeTime.SelectedValue.Split('-')[0]);
                DataTable T = new PackageBUS().GetById(dto.packageId);
                dto.subAccontCount = Convert.ToInt32(T.Rows[0]["subAccontCount"]);
                dto.emailCount = Convert.ToInt32(T.Rows[0]["emailCount"]);
                ClientRegisterBUS bus = new ClientRegisterBUS();
                bus.UpdateUpgrade(dto, getFunctionList());

                pnError.Visible = false;
                pnSuccess.Visible = true;
                lblSuccess.Text = "Đã nâng cấp gói thành công!!!";
                common.Common.logs(userLogin.Username + "-Đã nâng cấp gói thành công!!!", null, Common.logType.info);
                LoadData();
            }
            catch (Exception ex)
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = "Có lỗi xảy ra trong quá trình nâng cấp</br>" + ex.Message;
                common.Common.logs(userLogin.Username + "-btnUpgrade_Click", ex, Common.logType.error);
            }
        }

        private List<object> getFunctionList()
        {
            List<object> result = new List<object>();
            foreach (RepeaterItem item in rptListOptionsUpgrade.Items)
            {
                var lblID = item.FindControl("lblIDUpgrade");
                var check = item.FindControl("chkOptionsUpgrade");
                if (lblID != null && ((CheckBox)check).Checked)
                {
                    result.Add(((Label)lblID).Text);
                }
            }
            return result;
        }

        private string CheckBeforeUpgrade()
        {
            string message = "";
            int packageId = Convert.ToInt32(ddlUpgradeServices.SelectedValue.Split('-')[0]);
            if (packageId <= 0)
                message = "Chưa chọn gói dịch vụ";
            int limitId = Convert.ToInt32(ddlPackageLimitUpgrade.SelectedValue.Split('-')[0]);
            if (limitId <= 0)
                message = "chưa chọn hạng ngạch mail!";
            int packageTimeId = Convert.ToInt32(ddlUpgradeTime.SelectedValue.Split('-')[0]);
            if (packageTimeId <= 0)
                message = "Chưa chọn gói thời gian";
            return message;
        }
        private void LoadPackageTime()
        {
            //if (Session["LoadDropdownlist"] != null)
            //{
            SqlCommand cmd = new SqlCommand("Select * from tblPackageTime order by monthCount", ConnectionData._MyConnection);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            ConnectionData._MyConnection.Close();
            if (ConnectionData._MyConnection.State == ConnectionState.Closed)
            {
                ConnectionData._MyConnection.Open();
            }
            adapter.Fill(table);
            cmd.Dispose();
            adapter.Dispose();
            DataTable dtTemp = new DataTable();
            DataRow drTemp;
            dtTemp.Columns.Add("monthCount", typeof(String));
            dtTemp.Columns.Add("packageTimeId", typeof(String));
            dtTemp.Columns.Add("PackageTimeName", typeof(String));
            foreach (DataRow dr in table.Rows)
            {
                drTemp = dtTemp.NewRow();
                drTemp["monthCount"] = dr["monthCount"].ToString();
                drTemp["packageTimeId"] = dr["packageTimeId"] + "-" + dr["discount"] + "-" + dr["monthcount"];
                drTemp["PackageTimeName"] = dr["monthCount"].ToString() + " tháng";
                dtTemp.Rows.Add(drTemp);
            }
            ddlExtend.DataSource = dtTemp;
            ddlExtend.DataTextField = "PackageTimeName";
            ddlExtend.DataValueField = "packageTimeId";
            ddlExtend.DataBind();
            ddlUpgradeTime.DataSource = dtTemp;
            ddlUpgradeTime.DataTextField = "PackageTimeName";
            ddlUpgradeTime.DataValueField = "packageTimeId";
            ddlUpgradeTime.DataBind();
            //    Session["LoadDropdownlist"] = "Loaded";
            //}
        }
        protected void ddlUpgradeTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            TinhTien();

        }
        private double GetFeeRemain(int userid)
        {
            clientbus = new ClientBUS();
            DataTable dtClient = new DataTable();
            dtClient = clientbus.GetByID(userid);
            string email = dtClient.Rows[0]["email"].ToString();
            DateTime dateexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
            int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
            int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
            clientRegister = new ClientRegisterBUS();
            DataTable dtClientRegister = new DataTable();
            dtClientRegister = clientRegister.GetbyID(registerId);
            double feeRemain = 0, feeperday = 0;
            DateTime to = Convert.ToDateTime(dtClientRegister.Rows[0]["to"]);
            double.TryParse(dtClientRegister.Rows[0]["feePerday"] + "", out feeperday);
            feeRemain = (to - DateTime.Now).Days * feeperday;
            if (feeRemain < 0) feeRemain = 0;
            return feeRemain;
        }
        [WebMethod]
        public static string CalculateCost(string myparam)
        {
            string rasd = "Success catching event!!! ";
            return rasd;
        }
        [WebMethod]
        public static string sbGetData(string sdPreNo)
        {
            return sdPreNo + " hurray ";
        }
        protected void chkOptions_CheckedChanged(object sender, EventArgs e)
        {
            int value = 0;
            int Id = Convert.ToInt32(ddlLimitPackage.SelectedValue.ToString());
            pkglimitBus = new PackageLimitBUS();
            DataTable dtTemp = pkglimitBus.GetByUserIdPackageLimit(Id);
            foreach (RepeaterItem rptItems in rptListOptions.Items)
            {
                CheckBox chk = (CheckBox)rptItems.FindControl("chkOptions");
                Label lbl = (Label)rptItems.FindControl("lblCost");
                if (chk.Checked == true)
                {
                    value += Convert.ToInt32(lbl.Text);
                }
                else
                {
                    //value = value;
                }
            }
            int value2 = Convert.ToInt32(dtTemp.Rows[0]["cost"].ToString());
            lblSumCost.Text = (value + value2).ToString();
        }
        protected void chkOptionsUpgrade_CheckedChanged(object sender, EventArgs e)
        {
            TinhTien();
        }
        protected void ddlLimitPackage_SelectedIndexChanged(object sender, EventArgs e)
        {
            int value = 0;
            int Id = Convert.ToInt32(ddlLimitPackage.SelectedValue.ToString());
            pkglimitBus = new PackageLimitBUS();
            DataTable dtTemp = pkglimitBus.GetByUserIdPackageLimit(Id);
            foreach (RepeaterItem rptItems in rptListOptions.Items)
            {
                CheckBox chk = (CheckBox)rptItems.FindControl("chkOptions");
                Label lbl = (Label)rptItems.FindControl("lblCost");
                if (chk.Checked == true)
                {
                    value += Convert.ToInt32(lbl.Text);
                }
                else
                {
                    //value = value;
                }
            }
            int value2 = Convert.ToInt32(dtTemp.Rows[0]["cost"].ToString());
            lblSumCost.Text = (value + value2).ToString();
        }
        protected void rptListOptions_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                CheckBox chk = (CheckBox)e.Item.FindControl("chkOptions");
                Label lbl = (Label)e.Item.FindControl("lblCheck");
                Label lblid = (Label)e.Item.FindControl("lblID");
                string value = lbl.Text.Trim();
                int id = Convert.ToInt32(lblid.Text);
                if (id != null)
                {
                    if (value == "True")
                    {
                        chk.Checked = true;
                        chk.Enabled = false;
                    }
                    else
                    {
                        chk.Checked = true;
                    }
                }
            }
        }
        protected void btnEditOption_Click(object sender, EventArgs e)
        {
            int user = Convert.ToInt32(userLogin.UserId);
            clientbus = new ClientBUS();
            DataTable dtClient = new DataTable();
            dtClient = clientbus.GetByID(user);
            DateTime dateexpire = Convert.ToDateTime(dtClient.Rows[0]["expireDate"].ToString());
            int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
            int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
            clientRegister = new ClientRegisterBUS();
            DataTable dtClientRegister = new DataTable();
            dtClientRegister = clientRegister.GetbyID(registerId);
            int packageid = Convert.ToInt32(dtClientRegister.Rows[0]["packageId"].ToString());
            int limitId = Convert.ToInt32(ddlLimitPackage.SelectedValue.ToString());
            pkgBus = new PackageBUS();
            DataTable dtpackage = new DataTable();
            dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
            int SubAccount = Convert.ToInt32(dtpackage.Rows[0]["subAccontCount"].ToString());
            int totalFee = Convert.ToInt32(lblSumCost.Text);
            int registerType = 3;
            int packagetimeid = Convert.ToInt32(dtClientRegister.Rows[0]["packageTimeId"].ToString());
            string from = Convert.ToDateTime(dtClientRegister.Rows[0]["from"].ToString()).ToString("dd/MM/yyyy");
            string to = Convert.ToDateTime(dtClientRegister.Rows[0]["to"].ToString()).ToString("dd/MM/yyyy");
            string lastRegisterFrom = Convert.ToDateTime(dtClientRegister.Rows[0]["lastRegisterFrom"].ToString()).ToString("dd/MM/yyyy");
            string lastRegisterTo = Convert.ToDateTime(dtClientRegister.Rows[0]["lastRegisterTo"].ToString()).ToString("dd/MM/yyyy");
            int lastRegisterFee = Convert.ToInt32(dtClientRegister.Rows[0]["lastRegisterFee"].ToString());
            int lastRegisterFeeRemain = Convert.ToInt32(dtClientRegister.Rows[0]["lastRegisterFeeRemain"].ToString());
            int newregisterid = clientRegister.UpdateUpgrade(clientId, packageid, limitId, SubAccount, totalFee, registerType, packagetimeid, from, to, lastRegisterFrom, lastRegisterTo, lastRegisterFee, lastRegisterFeeRemain);
            clientbus.UpdateRegiterId(clientId, from, to, registerId, newregisterid);
            foreach (RepeaterItem rptItems in rptListOptions.Items)
            {
                CheckBox chk = (CheckBox)rptItems.FindControl("chkOptions");
                Label lbl = (Label)rptItems.FindControl("lblID");
                int functionId = Convert.ToInt32(lbl.Text);
                if (chk.Checked == true)
                {
                    clientFunction = new ClientFunctionBUS();
                    clientFunction.UpdateFunction(newregisterid, clientId, functionId);
                }
            }
            btnEditOption.Enabled = false;
            btnEditOption.CssClass = "button round text-upper";
            btnEditOption.Text = "Đã điều chỉnh chức năng gói!!!";
        }
        protected void rptListOptionsUpgrade_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            //{
            //    CheckBox chk = (CheckBox)e.Item.FindControl("chkOptionsUpgrade");
            //    Label lbl = (Label)e.Item.FindControl("lblCheckUpgrade");
            //    Label lblid = (Label)e.Item.FindControl("lblIDUpgrade");
            //    string value = lbl.Text.Trim();
            //    int id = Convert.ToInt32(lblid.Text);
            //    if (id != null)
            //    {
            //        if (value == "True")
            //        {
            //            chk.Checked = true;
            //            chk.Enabled = false;
            //        }
            //        else
            //        {
            //            chk.Checked = true;
            //        }
            //    }
            //}
        }
        protected void ddlPackageLimitUpgrade_SelectedIndexChanged(object sender, EventArgs e)
        {
            TinhTien();
        }
        protected void ddlUpgradeServices_SelectedIndexChanged(object sender, EventArgs e)
        {
            int packageId = Convert.ToInt32(ddlUpgradeServices.SelectedValue.Split('-')[0]);
            if (packageId != 0)
            {
                pkgFunctionBus = new PackageFunctionBUS();
                DataTable dtfunction = pkgFunctionBus.GetFunctionbyPackageId(Convert.ToInt32(packageId));

                rptListOptionsUpgrade.DataSource = dtfunction;
                rptListOptionsUpgrade.DataBind();
            }
            ddlUpgradeTime.SelectedValue = "0-0-0";
            ddlPackageLimitUpgrade.SelectedValue = ddlUpgradeServices.SelectedValue.Split('-')[1] + "-" + ddlUpgradeServices.SelectedValue.Split('-')[2];
            TinhTien();
        }
        double cost = 0, costperday = 0, costpermonth = 0;
        DateTime expireDate;
        void TinhTien()
        {
            double temp = 0;
            foreach (RepeaterItem item in rptListOptionsUpgrade.Items)
            {
                temp = 0;
                var check = item.FindControl("chkOptionsUpgrade");
                if (check != null && ((CheckBox)check).Checked)
                {
                    Label lCost = (Label)item.FindControl("lblCostUpgrade");
                    double.TryParse(lCost.Text, out temp);
                    cost += temp;
                }
            }
            var value = ddlPackageLimitUpgrade.SelectedValue;
            temp = 0;
            double.TryParse(value.Split('-')[1], out temp);
            cost += temp;
            int month = 0, discount = 0;
            var TimeId = ddlUpgradeTime.SelectedValue;
            if (int.TryParse(TimeId.Split('-')[2], out month) && month > 0)
            {
                int.TryParse(TimeId.Split('-')[1], out discount);
                cost = cost * month - (cost * month * discount / 100);
                costperday = cost / (DateTime.Now.AddMonths(month) - DateTime.Now.Date).Days;
                costpermonth = cost / month;
                double feeremain = 0;
                double.TryParse(lblFeeRemain.Text.Replace("$", ""), out feeremain);
                int day = (int)Math.Round(feeremain / costperday, 0);
                expireDate = DateTime.Now.AddMonths(month).AddDays(day);
                lblUpgradeExpireTime.Text = expireDate.ToString("dd/MM/yyyy");
            }
            lblFee.Text = cost.ToString("#,###.000'$'");
        }
    }
}